<template>
    <div class="setting-page">
        <div class="setting-title">
            项目设置
        </div>

        <!-- 基本信息卡片 -->
        <div class="info-card">
            <div class="card-header">
                <div class="card-header-title">
                    基本信息
                </div>
                <div class="card-header-action" v-permission="'project:manage:setting:edit'">
                    <div v-if="modeType == 'view'">
                        <el-button type="primary" @click="handleEdit">
                            <IconEdit class="mr-6px" />编辑
                        </el-button>
                    </div>
                    <div v-else>
                        <el-button type="primary" @click="handleSubmit">
                            确认
                        </el-button>
                        <el-button @click="handleClose">
                            取消
                        </el-button>
                    </div>
                </div>
            </div>
            <div class="card-content">
                <div class="form-container">
                    <el-form :model="form" ref="formRef" label-width="auto" label-suffix=":" :rules="rule"
                        v-loading="isLoading">
                        <el-form-item label="项目名称" prop="name" v-if="modeType === 'edit'">
                            <el-input v-model="form.name" />
                        </el-form-item>
                        <el-form-item label="项目名称" v-else>
                            {{ form.name || '-' }}
                        </el-form-item>
                        <el-form-item label="项目描述">
                            <el-input v-model="form.description" type="textarea" :rows="3" v-if="modeType === 'edit'" />
                            <div v-else>{{ form.description || '-' }}</div>
                        </el-form-item>
                        <el-form-item label="创建者">
                            {{ form.creator_name || '-' }}
                        </el-form-item>
                        <el-form-item label="创建时间">
                            {{ formatDayTime(form.create_time) }}
                        </el-form-item>
                    </el-form>
                </div>
            </div>

        </div>

        <!-- 危险操作卡片 -->
        <div class="danger-card" v-if="userStore.getUserInfo().id === projectStore.projectInfo.creator_id">
            <div class="card-header">
                <h2>危险操作</h2>
            </div>

            <div class="card-content">
                <div class="danger-item">
                    <div class="danger-info">
                        <label class="danger-label">移交项目</label>
                        <p class="danger-desc">将项目所有权转移给其他成员，此操作不可逆</p>
                    </div>
                    <el-button type="warning" @click="handleTransfer">
                        移交项目
                    </el-button>
                </div>

                <div class="danger-item">
                    <div class="danger-info">
                        <label class="danger-label">删除项目</label>
                        <p class="danger-desc">永久删除此项目及其所有数据，此操作不可恢复</p>
                    </div>
                    <el-button type="danger" @click="handleDelete">
                        删除项目
                    </el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { getProjectInfoApi, updateProjectInfo, deleteProjectApi } from '@/common/apis/project/index.ts';
import { useUserStore } from '@/store/modules/user';
import { formatDayTime } from '@/common/utils/datetime';
import router from '@/router';
import { useProjectStore } from '@/store/modules/project';

const userStore = useUserStore();
const projectStore = useProjectStore();
const modeType = ref('view');
const formRef = ref(null);
const isLoading = ref(false);
const originalForm = reactive({});
const form = reactive({
    name: '',
    description: '',
    creator_name: '',
    create_time: ''
});

const rule = reactive({
    name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
    ],
});

const handleClose = () => {
    // 恢复到编辑前的数据
    Object.assign(form, originalForm);
    modeType.value = 'view';
    formRef.value?.resetFields();
};

const handleEdit = () => {
    // 保存当前表单数据作为原始数据
    Object.assign(originalForm, form);
    modeType.value = 'edit';
};

const handleSubmit = async () => {
    try {
        isLoading.value = true;
        const valid = await formRef.value.validate();
        if (valid) {
            const { name, description } = form;
            const res = await updateProjectInfo({
                projectId: userStore.currentProjectId,
                name,
                description
            });
            ElMessage.success({ message: `${res.message}` });
            await init();
            modeType.value = 'view';
        } else {
            ElMessage({
                message: '请输入项目名称',
                type: 'warning',
            });
        }
    } catch (error) {
    } finally {
        isLoading.value = false;
    }
};

const handleTransfer = () => {
    ElMessage({
        message: '此功能暂未开发',
        type: 'warning',
    });
};
const handleDelete = () => {
    ElMessageBox.prompt(
        '删除后数据将不可恢复，本操作会删除项目下涉及的所有接口信息！<br><br>请输入项目名确认操作：',
        '删除项目？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            inputPlaceholder: '请输入项目名称',
            dangerouslyUseHTMLString: true,
            inputValidator: (value) => {
                if (!value) {
                    return '请输入项目名称';
                }
                if (value !== form.name) {
                    return '输入的项目名称不正确';
                }
                return true;
            },
        }
    )
        .then(async () => {
            const res = await deleteProjectApi({ projectId: userStore.currentProjectId });
            router.push('/');
            ElMessage.success({ message: `${res.message}` });
        })
        .catch(() => {
        });
};

const init = async () => {
    const { data } = await getProjectInfoApi({ projectId: userStore.currentProjectId });
    const { name, description, creator_name, create_time } = data;
    // 将获取的数据赋值给form
    Object.assign(form, { name, description, creator_name, create_time });
};

onMounted(() => {
    init();
});
</script>

<style lang="less" scoped>
.setting-page {
    height: 100%;
    background: var(--bg-primary);
    padding: 16px;
    overflow-y: auto;

    .setting-title {
        font-size: 20px;
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: 16px;
    }

    .info-card {
        padding: 16px;
        border: 1px solid var(--border-color);

        .card-header {
            display: flex;
            justify-content: space-between;

            .card-header-title {
                font-size: 16px;
                font-weight: 600;
                color: var(--text-primary);
                margin-bottom: 16px;
            }

            .card-header-action {}
        }

        .card-content {
            padding-left: 100px;

            .form-container {
                max-width: 500px;
            }
        }
    }

    .danger-card {
        margin-top: 36px;
        padding: 17px;
        border-radius: 8px;
        background: var(--card-error-bg);

        .card-header {
            margin-bottom: 16px;

            h2 {
                font-size: 16px;
                font-weight: 600;
                color: var(--text-primary);
                margin: 0;
            }
        }

        .card-content {
            .danger-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 16px 0;
                border-bottom: 1px solid var(--border-light);
                padding: 16px;
                border-radius: 8px;


                &:last-child {}

                &:first-child {
                    margin-bottom: 16px;
                }

                .danger-info {
                    flex: 1;
                    margin-right: 16px;

                    .danger-label {
                        font-size: 14px;
                        font-weight: 600;
                        color: var(--text-primary);
                        margin-bottom: 4px;
                    }

                    .danger-desc {
                        font-size: 12px;
                        color: var(--text-secondary);
                        margin: 0;
                        line-height: 1.4;
                    }
                }
            }
        }
    }
}
</style>